package com.gai.emp.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    //帮助我们获取sqlsession和mapper接口实现类，资源关闭，事务的提交回滚
    private static SqlSessionFactory ssf = null;
    //线程安全
    private static final ThreadLocal<SqlSession> thread = new ThreadLocal<SqlSession>();
    //读取文件
    static {
        try {
            InputStream resource = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //获取我们的sqlsession的方法
    public static SqlSession openSqlSession(){
        SqlSession session = thread.get();
        if (session == null) {
            session = ssf.openSession();
            thread.set(session);
        }
        return session;
    }

    public static SqlSession getSqlSession(){
        return ssf.openSession();
    }

    //关闭资源
    public static void close(){
        SqlSession session = thread.get();
        session.close();
        thread.remove();
    }
    //提交
    public static void commit(){
        //SqlSession session = thread.get();这个不一定保证拿到，可能在使用提交方法报空指针异常
        //通过openSqlSession去拿，就算是空也会帮我们创建一个
        SqlSession session = openSqlSession();
        session.commit();
        close();
    }
    //回滚
    public static void rollback(){
        SqlSession session = openSqlSession();
        session.rollback();
        close();
    }
    //设置获取mapper接口实现类
    public static <T> T getMapper(Class<T> t){
        return openSqlSession().getMapper(t);
    }
}
